import 'dart:math';

import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:videotop/jsonbean/peidbean.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../evenbus.dart';
import '../screen_service.dart';
import 'buygold.dart';
import 'buyvip.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

class PiPei extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _PiPei();
  }
}

class _PiPei extends State<PiPei> with TickerProviderStateMixin {
  AnimationController sccontroller;
  Animation animation;
  Animation<double> animation2;
  CameraController cameracontroller;
  bool show = true;
  bool pair = true;

  List<PdUser> list = [PdUser(icon: '', nickname: '', birth: '')];
  int pages = 1;
  int sex = 0;
  bool isadd = true; // 是否加载开关
  bool isskip = true; // 连点skip开关

  SharedPreferences spfs;
  int matchtimes = 0;
  int coins = 6;

  bool connecting = false;
  int sum = 50000 + Random().nextInt(10000);
  int sum2 = 2000 + Random().nextInt(1000);
  int sum3 = 40000 + Random().nextInt(10000);

  @override
  void initState() {
    super.initState();
    cameracontroller =
        CameraController(Util.cameras[1], ResolutionPreset.veryHigh);
    cameracontroller.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    });
    sccontroller =
        AnimationController(duration: Duration(seconds: 2), vsync: this);
    animation = CurvedAnimation(parent: sccontroller, curve: Curves.linear);
    animation2 = Tween(begin: 3.5, end: 0.5).animate(sccontroller);

    sccontroller.reverse(from: 1.0);
    sccontroller.addStatusListener((status) {
      if (status == AnimationStatus.dismissed) {
        sccontroller.reverse(from: 1.0);
        setState(() {});
      }
    });

    bus.on('coinsex', (arg) {
      sex = arg;
    });
  }

  @override
  Widget build(BuildContext context) {
    return cameracontroller != null ||cameracontroller.value.isInitialized
        ? Stack(
            children: [
              Container(
                height: ScreenService.height,
                child: AspectRatio(
                    aspectRatio: ScreenService.height / ScreenService.width,
                    child: CameraPreview(cameracontroller)),
              ),
              Center(
                  child: ScaleTransition(
                      scale: animation2,
                      child: FadeTransition(
                        opacity: animation,
                        child: Container(
                          height: 100,
                          width: 100,
                          child: CircularProgressIndicator(
                            value: 1.1,
                            strokeWidth: 8,
                            valueColor:
                                AlwaysStoppedAnimation<Color>(Colors.grey[200]),
                          ),
                        ),
                      ))),
              Container(
                width: ScreenService.width,
                height: ScreenService.height,
                color: Color(0xcf6046e7),
              ),
              pair
                  ? Stack(
                      children: [
                        Positioned(
                          top: 50,
                          left: 20,
                          child: GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () {
                              if (MyInfo.vip == 0) {
                                Util.sendAnalyticsActionEvent('match_monkey+');
                                showModalBottomSheet(
                                  context: context,
                                  isScrollControlled: true,
                                  backgroundColor: Colors.transparent,
                                  builder: (BuildContext context) {
                                    return BuyVip();
                                  },
                                );
                              }
                            },
                            child: Container(
                              height: 45,
                              padding: EdgeInsets.only(left: 15, right: 15),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular((30)),
                                color: Color(0x5f3F2C9F),
                              ),
                              child: Row(
                                children: [
                                  Image.asset(
                                    'assets/image/vipl.png',
                                    width: 30,
                                    height: 30,
                                  ),
                                  SizedBox(
                                    width: 5,
                                  ),
                                  Text(
                                    'Monkey+',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 15,
                                        fontFamily: 'my_medium'),
                                  )
                                ],
                              ),
                            ),
                          ),
                        ),
                        Visibility(
                            visible: show,
                            child: Align(
                                alignment: Alignment.center,
                                child: GestureDetector(
                                    onTap: () {
                                      pair = false;
                                      setState(() {});
                                      skip();
                                    },
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Text(
                                          'Tap to start video chatting',
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 16,
                                              fontFamily: 'my_medium'),
                                        ),
                                        Container(
                                          margin: EdgeInsets.only(top: 5),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.end,
                                            children: [
                                              Image.asset(
                                                'assets/image/video_pipei.png',
                                                width: 20,
                                                height: 22,
                                                fit: BoxFit.cover,
                                              ),
                                              Text(
                                                ' ${TextUtil.formatComma3(sum)} chatting',
                                                style: TextStyle(
                                                    color: Colors.grey[300],
                                                    fontSize: 13,
                                                    fontFamily: 'my_medium'),
                                              ),
                                            ],
                                          ),
                                        )
                                      ],
                                    )))),
                        Align(
                            alignment: Alignment.bottomCenter,
                            child: Container(
                              margin: EdgeInsets.only(bottom: 60),
                              width: ScreenService.width/2,
                              height: 80,
                              child: GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: chooseSex,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Image.asset(
                                          'assets/image/gb.png',
                                          width: 20,
                                          height: 20,
                                          fit: BoxFit.cover,
                                        ),
                                        SizedBox(width: 5,),
                                        Text(
                                          'Guys & Girls',
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 16,
                                              fontWeight:
                                              FontWeight.bold),
                                        ),
                                      ],
                                    ),
                                    SizedBox(
                                      height: 8,
                                    ),
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Image.asset(
                                          'assets/image/pipeic.png',
                                          width: 18,
                                          height: 18,
                                          fit: BoxFit.cover,
                                        ),
                                        Text(
                                          '  ${TextUtil.formatComma3(sum2)} filter',
                                          style: TextStyle(
                                              color: Colors.grey,
                                              fontSize: 12,
                                              fontFamily: 'my_medium'),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            )),
                      ],
                    )
                  : Stack(
                      children: [
                        Align(
                          alignment: Alignment.topCenter,
                          child: Container(
                            margin:
                                EdgeInsets.only(top: ScreenService.height / 4),
                            child: Column(
                              children: [
                                Container(
                                  height: ScreenService.width / 2.5,
                                  width: ScreenService.width / 2.5,
                                  child: ClipOval(
                                    child: Container(
                                        color: Colors.grey,
                                        padding: EdgeInsets.all(3),
                                        child: GestureDetector(
                                          onTap: () {
                                            Util.sendAnalyticsActionEvent(
                                                'message_space');
                                            Navigator.of(context)
                                                .push(MaterialPageRoute(
                                                    builder: (context) => Space(
                                                          uid: list[0].uid,
                                                        )));
                                          },
                                          child: ClipOval(
                                            child: list[0].icon.isNotEmpty
                                                ? CachedNetworkImage(
                                                    placeholder:
                                                        (context, url) =>
                                                            Container(
                                                      color: Color(0xff272443),
                                                      child: Center(
                                                        child: Image.asset(
                                                          'assets/image/space_bg.png',
                                                        ),
                                                      ),
                                                    ),
                                                    imageUrl:
                                                        '${list[0].icon}?x-oss-process=image/resize,h_400',
                                                    fit: BoxFit.cover,
                                                  )
                                                : Container(
                                                    color: Color(0xff272443),
                                                    child: Center(
                                                      child: Image.asset(
                                                        'assets/image/space_bg.png',
                                                      ),
                                                    ),
                                                  ),
                                          ),
                                        )),
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 20),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Container(
                                        constraints: BoxConstraints(
                                            maxWidth:
                                                ScreenService.width / 2.5),
                                        child: Text(
                                          "${list[0].nickname}",
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                              fontSize: 26,
                                              fontFamily: 'my_bold',
                                              color: Colors.white),
                                        ),
                                      ),
                                      const SizedBox(
                                        width: 10,
                                      ),
                                      Container(
                                        child: Text(
                                          list[0].birth.isNotEmpty
                                              ? "${Util.getAge(DateTime.parse(list[0].birth))}"
                                              : '',
                                          style: TextStyle(
                                              fontSize: 26,
                                              fontFamily: 'my_bold',
                                              color: Colors.white),
                                        ),
                                      ),
                                    ],
                                  ),
                                )
                              ],
                            ),
                          ),
                        ),
                        Align(
                          alignment: Alignment.bottomCenter,
                          child: Container(
                            height: 50,
                            margin: EdgeInsets.only(
                                bottom: ScreenService.height / 4),
                            width: ScreenService.width,
                            child: Row(
                              children: [
                                Expanded(
                                  child: GestureDetector(
                                    onTap: skip,
                                    child: Container(
                                      height: 50,
                                      margin:
                                          EdgeInsets.only(left: 30, right: 10),
                                      decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular((30)),
                                          color: Color(0xff3F2C9F)),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Image.asset(
                                            'assets/image/skip.png',
                                            width: 25,
                                            height: 25,
                                            fit: BoxFit.cover,
                                          ),
                                          SizedBox(
                                            width: 10,
                                          ),
                                          Text(
                                            'Skip',
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 16,
                                                fontWeight: FontWeight.bold),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                                Expanded(
                                    child: GestureDetector(
                                  onTap: handleCameraAndMic,
                                  child: Container(
                                    height: 50,
                                    margin:
                                        EdgeInsets.only(right: 30, left: 10),
                                    decoration: BoxDecoration(
                                        borderRadius:
                                            BorderRadius.circular((30)),
                                        color: Colors.yellow),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Image.asset(
                                          'assets/image/accept.png',
                                          width: 25,
                                          height: 25,
                                          fit: BoxFit.cover,
                                        ),
                                        SizedBox(
                                          width: 10,
                                        ),
                                        Text(
                                          'Accept',
                                          style: TextStyle(
                                              color: Colors.black,
                                              fontSize: 16,
                                              fontWeight: FontWeight.bold),
                                        ),
                                      ],
                                    ),
                                  ),
                                ))
                              ],
                            ),
                          ),
                        ),
                        Positioned(
                          bottom: ScreenService.height / 10,
                          child: Visibility(
                            visible: connecting,
                            child: Container(
                                width: ScreenService.width,
                                child: Center(
                                  child: SpinKitThreeBounce(
                                    color: Colors.white,
                                    size: 30,
                                  ),
                                )),
                          ),
                        ),
                        Positioned(
                            top: 40,
                            right: 20,
                            child: GestureDetector(
                              onTap: () {
                                pair = true;
                                setState(() {});
                              },
                              child: Container(
                                padding: EdgeInsets.all(10),
                                child: Image.asset(
                                  'assets/image/homex.png',
                                  width: 18,
                                  height: 18,
                                ),
                              ),
                            ))
                      ],
                    ),
            ],
          )
        : Center(
            child: Container(
            width: 20,
            height: 20,
            child: CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Colors.grey),
              strokeWidth: 2,
            ),
          ));
  }

  chooseSex() {
    Util.sendAnalyticsActionEvent('match_filter');
    show = false;
    setState(() {});
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return SizedBox(
          child: Peidui(sex),
        );
      },
    ).then((value) {
      show = true;
      if (mounted) setState(() {});
    });
  }

  getData(int page, int sex) async {
    List<PdUser> newlist = await Util.getPeiduiData(page, sex);
    if (newlist.length > 0) {
      list.addAll(newlist);
      pages++;
      if (isadd) {
        bus.emit('pairsum');
        list.removeAt(0);
        isadd = false;
        isskip = true;
        connecting = false;
        setState(() {});
        if (sex != 0) {
          MyInfo.gold -= coins;
          Util.setGold(MyInfo.gold, 2);
        }
      }
    } else {
      isadd = false;
      isskip = true;
      connecting = false;
      setState(() {});
      Util.showToast('no data');
    }
  }

  skip() async {
    connecting = true;
    setState(() {});
    Util.sendAnalyticsActionEvent('match_skip');
    if (MyInfo.vip != 0) coins = 3;
    if (isskip) {
      if (sex != 0) {
        if (MyInfo.gold >= coins) {
          isskip = false;
          if (list.length <= 1) {
            isadd = true;
            getData(pages, sex);
          } else {
            list.removeAt(0);
            isskip = true;
            setState(() {});
          }
        } else {
          Navigator.of(context)
              .push(MaterialPageRoute(builder: (context) => BuyGold()));
        }
      } else {
        if (MyInfo.vip != 0) {
          isskip = false;
          if (list.length <= 1) {
            isadd = true;
            getData(pages, sex);
          } else {
            list.removeAt(0);
            isskip = true;
            setState(() {});
          }
        } else {
          spfs = await SharedPreferences.getInstance();
          int day = spfs.getInt('day') ?? 0;
          if (day == DateTime.now().day) {
            matchtimes = spfs.getInt('matchtimes') ?? 0;
          } else {
            spfs.setInt('day', DateTime.now().day);
            matchtimes = 0;
          }

          matchtimes++;
          if (matchtimes > 5) {
            pair = true;
            setState(() {});
            showModalBottomSheet(
              context: context,
              isScrollControlled: true,
              backgroundColor: Colors.transparent,
              builder: (BuildContext context) {
                return BuyVip(
                  index: 5,
                );
              },
            );
          } else {
            spfs.setInt('matchtimes', matchtimes);
            isskip = false;
            if (list.length <= 1) {
              isadd = true;
              getData(pages, sex);
            } else {
              list.removeAt(0);
              isskip = true;
              setState(() {});
            }
          }
        }
      }
    }
  }

  handleCameraAndMic() async {
    Util.sendAnalyticsActionEvent('match_accept');
    Map<String, dynamic> map = {'yuid': list[0].uid, 'vip': MyInfo.vip};
    Util.sendAnalyticsActionEvent('SPACE_VIDEO', map: map);
    if (MyInfo.gold < list[0].price) {
      Navigator.of(context)
          .push(MaterialPageRoute(builder: (context) => BuyGold()));
    } else {
      Util.requestCamera(context).then((value) {
        if (value) {
          Util.requestVoice(context).then((value) {
            if (value) {
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                return CallPage(
                  true,
                  price: list[0].price,
                  uid: list[0].uid,
                  role: ClientRole.Broadcaster,
                  channelName: '${MyInfo.uid}_${list[0].uid}',
                  nickname: list[0].nickname,
                  icon: list[0].icon,
                  country: list[0].country,
                  countrycode: list[0].code,
                  vip: list[0].vip,
                  birth: list[0].birth,
                );
              }));
            } else {
              Util.showToast('${S.of(context).mic}');
            }
          });
        } else {
          Util.showToast('${S.of(context).photoquanxian}');
        }
      });
    }
  }

  @override
  void dispose() {
    cameracontroller?.dispose();
    sccontroller.dispose();
    super.dispose();
  }
}
